package com.qaplus.service.impl;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import com.qaplus.common.CommonBusiLogic;
import com.qaplus.entity.QaClass;
import com.qaplus.entity.QaUser;
import com.qaplus.entity.vo.Page;
import com.qaplus.entity.vo.ResponseData;
import com.qaplus.mapper.QaClassMapperExt;
import com.qaplus.service.ClassService;
import com.qaplus.service.UserService;

@Service
public class ClassServiceImpl implements ClassService {
	@Resource
	private QaClassMapperExt classMapperExt;
	@Resource
	private UserService userService;

	private static final String DELIMETER = ",";

	@Cacheable(value="classes")
	@Override
	public ResponseData<QaClass> queryAllClassForPage(Page page) {
		//如果前端有可能传begin end 也有可能传 current length
		if(page!=null && page.getEnd()==0){
			CommonBusiLogic.setPageBeginByPage(page);
		}
		return new ResponseData<QaClass>(classMapperExt.queryAllClassForPage(page), classMapperExt.countAllClassForPage());
	}

	@Override
	public int updateClass(QaClass clazz) {
		return classMapperExt.updateByPrimaryKeySelective(clazz);
	}

	@Override
	public int addClass(QaClass clazz, Long teacherId) {
		// 添加班级，并且分配给老师
		classMapperExt.insertSelective(clazz);

		QaUser user = userService.queryById(teacherId);

		user.setId(teacherId);
		// 必须保证class_id是以,开头
		user.setClassId(user.getClassId() + DELIMETER + clazz.getId());

		return userService.updateByPrimaryKeySelective(user);
	}

	@Override
	public QaClass selectByPrimary(Long id) {
		return classMapperExt.selectByPrimaryKey(id);
	}

	@Override
	public List<QaClass> queryMyClass() {
		QaUser user = userService.getCurrentUserBySession();
		String classes[] = user.getClassId().split(DELIMETER);
		List<QaClass> classList=new ArrayList<QaClass>();
		for (String classId : classes) {
			if (StringUtils.isEmpty(classId)) {
				continue;
			}
			QaClass clazz=classMapperExt.selectByPrimaryKey(Long.parseLong(classId));
			if(null!=clazz){
				classList.add(clazz);
			}
		}
		return classList;
	}

	@Override
	public List<QaClass> selectAllClasses() {
		return classMapperExt.selectByExample(null);
	}

}
